package com.zzy.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ReadFileAndSave<T> {

    private Class<T> clazz;

    public ReadFileAndSave(Class<T> clazz) {
        this.clazz = clazz;
    }

    /**
     * 把 mapper 作为参数传递近来
     * @param saveMapper
     */
    public void readSave( Object  saveMapper ) {
        try {
            String fileLines[] = new String[]{"a1,b1,c1", "a2,b2,c2"};//假设这是从文件读取的数据
            Field[] allFields = clazz.getDeclaredFields();
            Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
            int filedNums = 0;
            for (int i = 0; i < allFields.length; i++) {
                Field field = allFields[i];
                field.setAccessible(true);// 设置类的私有字段属性可访问
                fieldsMap.put(filedNums, field);
                filedNums++;
            }
            List<T> list = new ArrayList<>();
            for (String lines : fileLines) {
                //新建一个 实体类
                T entity = clazz.newInstance();
                // 循环实体类 属性
                String filedData[] = lines.split(",");// 这个值 一定要比 实体类的属性 多，否则报错
                for (int index = 0; index < filedNums; index++) {
                    Field field = fieldsMap.get(index);//获取filed 属性
                    field.set(entity, filedData[index]); //给属性赋值
                }
                list.add(entity);
            }

            System.out.println(list.size());
            System.out.println(list);
            System.out.println("通过反射调用save方法。。。。");

            Method method = saveMapper.getClass().getMethod("saveDataBatch",List.class);
            method.invoke(saveMapper,list);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
